<?php

error_reporting(E_STRICT | E_ALL);
date_default_timezone_set('America/New_York');
ini_set('display_errors', 1);
set_time_limit(60*60);
ini_set('memory_limit', '128M');

require_once "config.php";
require_once dirname(__FILE__). '/util/connection.class.php';
require_once dirname(__FILE__). '/util/record.php';

$dbconn = Connection::getInstance();

$sites = getSites($dbconn);
foreach($sites as $siteInfo){
	$moneySign = (trim(strtolower($sitesInfo['locale'])) == 'uk')? '£' : '$';
	$tag = 'day2';
	$day2Users = getday2Users($dbconn, $siteInfo['id']);
	$day2template = getTemplate($tag, $siteInfo['template']);
	if(!empty($day2Users)){
		foreach($day2Users as $user){
			addNewEmail($tag, $siteInfo['template'], $day2template, $siteInfo['domain'], $siteInfo['sitename'], array('firstname'=>$user['firstname'], 'email'=>$user['email'], 'jackpot'=>$siteInfo['jackpot'], 'won'=>$user['won'], 'uid'=>$user['id']), $dbconn);
		}		
	}
	unset($day2Users);
	unset($day2template);
	
	$tag= 'day4';
	$day4Users = getday4Users($dbconn, $siteInfo['id']);
	$day4template = getTemplate($tag, $siteInfo['template']);
	if(!empty($day4Users)){
		foreach($day4Users as $user){
			addNewEmail($tag, $siteInfo['template'], $day4template, $siteInfo['domain'], $siteInfo['sitename'], array('firstname'=>$user['firstname'], 'email'=>$user['email'], 'jackpot'=>$siteInfo['jackpot'], 'won'=>$user['won'], 'uid'=>$user['id']), $dbconn);
		}		
	}
	unset($day4Users);
	unset($day4template);
	
	$tag = 'week2';
	$week2Users = getweek2Users($dbconn, $siteInfo['id']);
	$week2template = getTemplate($tag, $siteInfo['template']);
	if(!empty($week2Users)){
		foreach($week2Users as $user){
			addNewEmail($tag, $siteInfo['template'], $week2template, $siteInfo['domain'], $siteInfo['sitename'], array('firstname'=>$user['firstname'], 'email'=>$user['email'], 'jackpot'=>$siteInfo['jackpot'], 'won'=>$user['won'], 'uid'=>$user['id']), $dbconn);
		}		
	}
	unset($week2Users);
	unset($week2template);
	
	$tag = 'week3';
	$week3Users = getweek3Users($dbconn, $siteInfo['id']);
	$week3template = getTemplate($tag, $siteInfo['template']);
	$top5winners = getAllLeaders_5($dbconn, $siteInfo['id']);
	$top5Tab_html = "<table>";
	$top5Tab_html .="<tr>
						<th>Rank</th>
						<th>Name</th>
						<th>Location</th>
						<th>Winnings</th>
					</tr>";
	if($top5winners){
		for($i = 0; $i < count($top5winners); $i++){
			$top5Tab_html .= "<tr>";
				$top5Tab_html .= "<td>";
					$top5Tab_html .= $i+1;
				$top5Tab_html .= "</td>";
				$top5Tab_html .= "<td>";
					$top5Tab_html .= $top5winners[$i]['username'];
				$top5Tab_html .= "</td>";
				$top5Tab_html .= "<td>";
					$top5Tab_html .= $top5winners[$i]['location'];
				$top5Tab_html .= "</td>";
				$top5Tab_html .= "<td>" . $moneySign;
					$top5Tab_html .= $top5winners[$i]['won'];
				$top5Tab_html .= "</td>";
			$top5Tab_html .= "</tr>";
		}
	}
	$top5Tab_html .= "</table>";
	if(!empty($week3Users)){
		foreach($week3Users as $user){
			addNewEmail($tag, $siteInfo['template'], $week3template, $siteInfo['domain'], $siteInfo['sitename'], array('firstname'=>$user['firstname'], 'email'=>$user['email'], 'jackpot'=>$siteInfo['jackpot'], 'won'=>$user['won'], 'top5Tab'=>$top5Tab_html, 'uid'=>$user['id']), $dbconn);
		}		
	}
	unset($week3Users);
	unset($week3template);
}

function getSites(Connection $db)
{
	$sql = "SELECT id, template, locale, domain, name as sitename, jackpot FROM `sites` ";
	try{
		$ret = $db->query($sql);
		return $ret;
	}catch (Exception $e){
		QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
		throw new Model_Exception($e->getMessage(), $e->getCode());
	}
}

function getday2Users(Connection $db, $site_id)
{
	$now = time();
	$yesterdaystart = strtotime(date('Y-m-d 00:00:00', time()-60*60*24), time());
	$yesterdayend = strtotime(date('Y-m-d 23:59:59', time()-60*60*24), time());
	$sql = "SELECT id, email, firstname, balance AS won, concat(firstname, ' ', lastname)as name, created FROM `users` WHERE site_id=? AND unsub=0 AND created >= ? AND created <= ?";
	try{
		return $db->query($sql, array($site_id, $yesterdaystart, $yesterdayend));
	}catch (Exception $e){
		QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
		throw new Model_Exception($e->getMessage(), $e->getCode());
	}
}
function getday4Users(Connection $db, $site_id)
{
	$now = time();
	$before3daysstart = strtotime(date('Y-m-d 00:00:00', time()-60*60*24*3), time());
	$before3daysend = strtotime(date('Y-m-d 23:59:59', time()-60*60*24*3), time());
	$sql = "SELECT id, email, firstname, balance AS won, concat(firstname, ' ', lastname)as name, created FROM `users` WHERE site_id=? AND unsub=0 AND created >= ? AND created <= ?";
	try{
		return $db->query($sql, array($site_id, $before3daysstart, $before3daysend));
	}catch (Exception $e){
		QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
		throw new Model_Exception($e->getMessage(), $e->getCode());
	}
}
function getweek2Users(Connection $db, $site_id)
{
	$now = time();
	$beforeweekstart = strtotime(date('Y-m-d 00:00:00', time()-60*60*24*7), time());
	$beforeweekend = strtotime(date('Y-m-d 23:59:59', time()-60*60*24*7), time());
	$sql = "SELECT id, email, firstname, balance AS won, concat(firstname, ' ', lastname)as name, created FROM `users` WHERE site_id=? AND unsub=0 AND created >= ? AND created <= ?";
	try{
		return $db->query($sql, array($site_id, $beforeweekstart, $beforeweekend));
	}catch (Exception $e){
		QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
		throw new Model_Exception($e->getMessage(), $e->getCode());
	}
}
function getweek3Users(Connection $db, $site_id)
{
	$now = time();
	$before2weeksstart = strtotime(date('Y-m-d 00:00:00', time()-60*60*24*14), time());
	$before2weeksend = strtotime(date('Y-m-d 23:59:59', time()-60*60*24*14), time());
	$sql = "SELECT id, email, firstname, balance AS won, concat(firstname, ' ', lastname)as name, created FROM `users` WHERE site_id=? AND unsub=0 AND created >= ? AND created <= ?";
	try{
		return $db->query($sql, array($site_id, $before2weeksstart, $before2weeksend));
	}catch (Exception $e){
		QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
		throw new Model_Exception($e->getMessage(), $e->getCode());
	}
}

function getAllLeaders_5(Connection $db, $siteid)
{
	try{
		$sql = "select concat(concat(firstname, ' '),upper(left(lastname,1))) as username, won
				, concat(concat(city, ', '), state) as location from users where site_id = ? and won>0 order by won desc limit 0, 5";
		$result = $db->query($sql, array($siteid));
		if(count($result) >= 1){
			return $result;
		}
		else{
			return false;
		}
	}catch (Exception $e){
		QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
		throw new Model_Exception($e->getMessage(), $e->getCode());
	}
}
function addNewEmail($tag, $site_template, $template, $domain, $sitename, $args, Connection $db)
{
	if($template){
		$content = translate($template,  $args);
		$subject = getEmailSubject($tag, $site_template, $args);
		if(addSentEmailToDb($sitename, 'no-reply@' . strtolower($domain), $subject, $args['email'], $content, $db, $tag)){
			if(replaceEmail_contentEmid($db)){
				$record = new Record($args['uid']);
				$record->addEmailSentRecording($tag);
				return true;
			}
		}
	}
	return false;		
}

function replaceEmail_contentEmid(Connection $db)
{
	$emId = $db->getLastInsert();
	$sql = "UPDATE `emails` SET `content` = REPLACE(content,'[[emailId]]', ?), sent=0 where id=?";
	try{
		return $db->execute($sql,array($emId, $emId));
	}catch (Exception $e){
		QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
		throw new Model_Exception($e->getMessage(), $e->getCode());
	}
}

function getTemplate($tag, $site_template)
{
	$template_name = TEMPLATE_ROOT .'/'. $site_template . '/email/' . $tag . '.html';
	if(file_exists($template_name))
	{
		if(is_readable($template_name))
		{
			$template = file_get_contents($template_name);
			return $template;
		}
	}
}


function addSentEmailToDb($sender, $sendfrom, $subject, $sendto, $content, Connection $db, $tag){
	$sql = "insert into emails set sender=?, sendfrom=?, subject=?, sendto=?, content=?, created=?, sent=?, email_type=?, priority=20";
	try{
		return $db->execute($sql,array($sender, $sendfrom, $subject, $sendto, $content, time(), 1, $tag));
	}catch (Exception $e){
		QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
		throw new Model_Exception($e->getMessage(), $e->getCode());
	}
}

function translate($content, $args){
	foreach ($args as $k => $v){
		$content = str_replace('[[' . $k . ']]', $v, $content);
	}
	return $content;
}

function getEmailSubject($tag, $site_template, $args){
	$config = TEMPLATE_ROOT. '/' .$site_template . '/email/email.ini';
	$subjects = parse_ini_file($config);
	$subject = isset($subjects[$tag]) ? $subjects[$tag] :false;
	if($subject){
		return translate($subject, $args);
	}
	return '';
}